package io.renren.modules.sys.controller;

import java.util.*;

import io.renren.common.exception.RRException;
import io.renren.common.utils.RandomUtil;
import io.renren.common.validator.ValidatorUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.text.DecimalFormat;

import java.io.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.sys.entity.FyUsersEntity;

import io.renren.modules.sys.entity.FyTeacherEntity;
import io.renren.modules.sys.entity.FyParentStudentEntity;
import io.renren.modules.sys.service.FyUsersService;
import io.renren.modules.sys.service.FyParentStudentService;
import io.renren.modules.sys.service.FyTeacherService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.springframework.web.multipart.MultipartFile;


import org.apache.poi.ss.usermodel.*;



/**
 * 
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2019-03-01 10:35:38
 */
@RestController
@RequestMapping("sys/fyusers")
public class FyUsersController {
    @Autowired
    private FyUsersService fyUsersService;

    @Autowired
    private FyTeacherService fyTeacherService;


    @Autowired
    private FyParentStudentService  fyParentStudentService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:fyusers:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = fyUsersService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{userId}")
    @RequiresPermissions("sys:fyusers:info")
    public R info(@PathVariable("userId") Integer userId){
        FyUsersEntity fyUsers = fyUsersService.getById(userId);

        return R.ok().put("fyUsers", fyUsers);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:fyusers:save")
    public R save(@RequestBody FyUsersEntity fyUsers){
        fyUsersService.save(fyUsers);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:fyusers:update")
    public R update(@RequestBody FyUsersEntity fyUsers){
        ValidatorUtils.validateEntity(fyUsers);
        fyUsersService.updateById(fyUsers);
        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:fyusers:delete")
    public R delete(@RequestBody Integer[] userIds){
        fyUsersService.removeByIds(Arrays.asList(userIds));

        return R.ok();
    }

    /**
     * 查询所有用户信息
     */
    @RequestMapping("/alllist")
    @RequiresPermissions("sys:fyusers:alllist")
    public R alllist(){
        List<FyUsersEntity> alllist = fyUsersService.list(new QueryWrapper<FyUsersEntity>());
        return R.ok().put("alllist", alllist);
    }

    /**
     * 查询所有老师信息
     */
    @RequestMapping("/allteacherlist")
    @RequiresPermissions("sys:fyusers:allteacherlist")
    public R allteacherlist(){
        List<FyTeacherEntity> teacherlist = fyTeacherService.list(new QueryWrapper<FyTeacherEntity>());
        List<FyUsersEntity> alllist = new ArrayList<FyUsersEntity>();
        if(teacherlist!=null && teacherlist.size()>0){
            for(int i=0;i<teacherlist.size();i++){
                FyTeacherEntity teacherEntity = teacherlist.get(i);
                FyUsersEntity usersEntity = fyUsersService.getById(teacherEntity.getUserId());
                alllist.add(usersEntity);
            }
        }
        return R.ok().put("alllist", alllist);
    }


    /**
     * 上传文件
     */
    @RequestMapping("/upload")
    @RequiresPermissions("sys:fyusers:upload")
    public R upload(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        if (multipartFile.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        Workbook workbook = null;
        int totalNum = 0;
        String sn = RandomUtil.generateString(16);
        String path =  "C:\\" + sn+".xlsx";
        File file = new File(path);
        InputStream input = multipartFile.getInputStream();
        //FileCopyUtils.copy(multipartFile.getBytes(), file);
        workbook = WorkbookFactory.create(input);
        List<FyParentStudentEntity> list = new ArrayList<FyParentStudentEntity>();
        /*遍历sheet页*/
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            /*统计导入的总条数，要是你的excell包含了表头，就不用加1了*/
            if (sheet.getLastRowNum() > 0) {
                totalNum += sheet.getLastRowNum();
            }
            /*遍历行，这里j的初始值取1是因为我的表格里第一行是表头*/
            for (int j = 1; j < sheet.getPhysicalNumberOfRows(); j++) {
                Row row = sheet.getRow(j);
                /*解析列，下标从0开始*/
                Cell cell1 = row.getCell(0);
                Cell cell2 = row.getCell(1);
                Cell cell3 = row.getCell(2);
                Cell cell4 = row.getCell(3);
                Cell cell5 = row.getCell(4);

                if (cell1 == null || cell2 == null||cell4 == null) {
                    continue;
                }
                DecimalFormat df = new DecimalFormat("#");
                FyParentStudentEntity entity = new FyParentStudentEntity();
                entity.setSchoolId((int)cell1.getNumericCellValue());
                entity.setStudentClassId((int)cell2.getNumericCellValue());
                entity.setStudentname(cell3.toString());
                entity.setTelphone(df.format(cell4.getNumericCellValue()));
                entity.setRelationship(cell5.toString());
                list.add(entity);
            }
            /*持久化：批量新增*/
            fyParentStudentService.saveBatch(list);
        }
        /*解析完删除此路径下的文件*/

        file.delete();

        return R.ok().put("totalNum", totalNum);
    }

}
